package handlers

import (
	"encoding/json"
	"fmt"
	"luntan/pkg/models"
	"net/http"

	"github.com/google/uuid"
	"github.com/gorilla/sessions"
)

type Message struct {
	// status: 0->success
	Status int `json:"status"`
	// say something to notfy
	Msg string `json:"msg,omitempty"`
	// pass data to js
	Data []models.User `json:"data,omitempty"`
}

var Session_store = sessions.NewCookieStore([]byte("alongstory"))

func Session(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "http://localhost:8080")
	w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

	msg := Message{Msg: "login success"}
	session, _ := Session_store.Get(req, "session-luntan")
	sid, _ := session.Values["sid"].(string)
	if sid == "" {
		sid = uuid.New().String()
		session.Values["sid"] = sid
		session.Save(req, w)
	}
	// auth
	authed, _ := session.Values["authed"].(bool)
	if !authed {
		msg.Status = -1
		msg.Msg = "login first"
		Resp(w, &msg)
		return
	}
	msg.Msg = "session success"
	Resp(w, &msg)
}

func Resp(w http.ResponseWriter, msg *Message) {
	if w == nil || msg == nil {
		fmt.Println("call respErr with invalid w/msg")
		return
	}

	buf, err := json.Marshal(&msg)
	if err != nil {
		w.Write([]byte(fmt.Sprintf(`{"status":-300,"msg":"%s"}`, err.Error())))
		fmt.Println(err.Error())
		return
	}
	w.Write(buf)
}

func ListResp(w http.ResponseWriter, msg *ListMessage) {
	if w == nil || msg == nil {
		fmt.Println("call respErr with invalid w/msg")
		return
	}

	buf, err := json.Marshal(&msg)
	if err != nil {
		w.Write([]byte(fmt.Sprintf(`{"status":-300,"msg":"%s"}`, err.Error())))
		fmt.Println(err.Error())
		return
	}
	w.Write(buf)
}

func ComtResp(w http.ResponseWriter, msg *CommitMessage) {
	if w == nil || msg == nil {
		fmt.Println("call respErr with invalid w/msg")
		return
	}

	buf, err := json.Marshal(&msg)
	if err != nil {
		w.Write([]byte(fmt.Sprintf(`{"status":-300,"msg":"%s"}`, err.Error())))
		fmt.Println(err.Error())
		return
	}
	w.Write(buf)
}

func UserResp(w http.ResponseWriter, msg *UserMessage) {
	if w == nil || msg == nil {
		fmt.Println("call respErr with invalid w/msg")
		return
	}

	buf, err := json.Marshal(&msg)
	if err != nil {
		w.Write([]byte(fmt.Sprintf(`{"status":-300,"msg":"%s"}`, err.Error())))
		fmt.Println(err.Error())
		return
	}
	w.Write(buf)
}
